package com.wang.service;

import java.util.List;

import com.wang.dao.HomeCostDao;
import com.wang.pojo.HomeCost;
import com.wang.pojo.Page;
import com.wang.pojo.User;

public class HomeCostService {

    HomeCostDao homeCostDao = new HomeCostDao();

    //新增消费账单
    public int add(HomeCost homecost) {
        return homeCostDao.add(homecost);
    }

    //删除消费账单
    public int delete(int id) {
        return homeCostDao.delete(id);
    }

    //修改消费账单
    public int update(HomeCost homecost) {
        return homeCostDao.update(homecost);
    }

    //关键字查询
    public List<HomeCost> query(String keyword) {
        return homeCostDao.query(keyword);
    }


    //由id查找某条消费记录
    public HomeCost getHomeCostById(int id) {
        return homeCostDao.getHomeCostById(id);
    }

    public Page<HomeCost> page(int pageNo, int pageSize, User user, int user_id) {

        Page<HomeCost> page = new Page<HomeCost>();

        page.setPageSize(pageSize);

        Integer pageTotalCount;

        if (user_id == 0) {
            pageTotalCount = homeCostDao.queryForPageTotalCount(user);
        } else {
            pageTotalCount = homeCostDao.queryForPageTotalCountByUserId(user, user_id);
        }

        page.setPageTotalCount(pageTotalCount);

        Integer pageTotal = pageTotalCount / pageSize;  //计算总页数

        if (pageTotalCount % pageSize != 0) pageTotal++;    //不能整除要多一页

        page.setPageTotal(pageTotal);

        page.setPageNo(pageNo);

        int begin = (page.getPageNo() - 1) * pageSize;  //套用公式计算begin

        List<HomeCost> items;

        if (user_id == 0) {
            items = homeCostDao.queryForPageItems(begin, pageSize, user);
        } else {
            items = homeCostDao.queryForPageItemsByUserId(begin, pageSize, user, user_id);
        }
        page.setItems(items);

        return page;
    }

    public Page<HomeCost> pageByKeyword(int pageNo, int pageSize, String keyword, User user) {

        Page<HomeCost> page = new Page<HomeCost>();

        page.setPageSize(pageSize);

        Integer pageTotalCount = homeCostDao.queryForPageTotalCountByKeyword(keyword, user);

        page.setPageTotalCount(pageTotalCount);

        Integer pageTotal = pageTotalCount / pageSize;  //计算总页数

        if (pageTotalCount % pageSize != 0) pageTotal++;    //不能整除要多一页

        page.setPageTotal(pageTotal);

        page.setPageNo(pageNo);

        int begin = (page.getPageNo() - 1) * pageSize;  //套用公式计算begin

        List<HomeCost> items = homeCostDao.queryForPageItemsByKeyword(begin, pageSize, keyword, user);
        page.setItems(items);
        return page;
    }
}
